﻿
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;


namespace Excel2Word
{
    public class WordReportManager
    {

        public static string basePath = null;
        public const string frm_body = "body";
        public const string frm_update_time = "updateTime";
        public const string frm_form_id = "formId";
        public string modelId;
        public string taskId;

        public WordReportManager(string modelId, string taskId)
        {
            this.modelId = modelId;
            this.taskId = taskId;
        }


        //public string WriteWord()
        //{


        //    Loading loading = new Loading();
        //    loading.TopMost = true;
        //    loading.Show();

        //    try
        //    {
        //        //1、从数据库中读取该任务对应的模版路径和更新时间
        //        var siteReportsDs = Dics.GetDbClient().GetDataFromDb(Dics.connStr, string.Format("SELECT * FROM t_report_model where belong_model_id = '{0}'", modelId));
        //        System.Windows.Forms.Application.DoEvents();
        //        if (siteReportsDs == null || siteReportsDs.Tables[0].Rows.Count == 0)
        //        {
        //            return "没有找到相应的模版！";
        //        }

        //        var siteReportModelDr = siteReportsDs.Tables[0].Rows[0];
        //        var fileId = siteReportModelDr[FrmDefineWordReport.rp_server_file_name].ToString();
        //        var updateTimeStr = Utility.DateTimeToTimaStamp((DateTime)siteReportModelDr[FrmDefineWordReport.rp_update_time]).ToString();

        //        //2、读取本地所有的站点信息表，如果名称中包含项目ID，但时间不对，删除，如果全对，则标记出来
        //        if (basePath == null) basePath = CpdatCloudClient.Interop.CommonUitiliy.GetCodeBase(this.GetType());
        //        var fileDir = basePath + "\\SiteTable\\";

        //        var dirInfo = new System.IO.DirectoryInfo(fileDir);

        //        string thisFileName = fileDir + fileId + "." + updateTimeStr + ".docx";

        //        if (!File.Exists(thisFileName))
        //        {
        //            thisFileName = null;
        //        }



        //        //3、如果没有在本地找到对应模版文件，那么从服务器进行下载
        //        string errorStr = null;
        //        if (thisFileName == null) thisFileName = DownLoadSiteModelFromServer(fileId, updateTimeStr, out errorStr);



        //        if (errorStr != null) return errorStr;



        //        var startUpTempFiles = Directory.GetFiles(System.Windows.Forms.Application.StartupPath).Where(the => the.EndsWith(".docx"));
        //        foreach (var each in startUpTempFiles)
        //        {
        //            try
        //            {
        //                File.Delete(each);
        //            }
        //            catch
        //            {

        //            }
        //        }
                



        //        var tempPath = System.Windows.Forms.Application.StartupPath + "\\temp_" + Guid.NewGuid().ToString() +".docx";

        //        File.Delete(tempPath);


        //        File.Copy(thisFileName, tempPath);

                 
        //        thisFileName = tempPath;


        //        //为了不让界面卡死 临时先这么写把 by wanglong
        //        System.Windows.Forms.Application.DoEvents();

        //        //4、打开指定的WORD，并寻找指定命名
        //        var acDoc = WordOperation.GetDocByFullName(thisFileName);

            

        //        acDoc.Application.Visible = false;

        //        if (acDoc == null) return "打开文件失败";

        //        //5、获取该任务的填报信息

        //        var formDs = Dics.GetDbClient().GetDataFromDb(Dics.connStr, string.Format("SELECT * FROM t_form WHERE formId = '{0}'", taskId));

        //        if (formDs == null || formDs.Tables[0].Rows.Count == 0)
        //        {
        //            return "数据库查询任务信息失败！";
        //        }

        //        var pageDic = JsonConvert.DeserializeObject<Dictionary<string, ModelEleData>>(formDs.Tables[0].Rows[0][frm_body].ToString());




        //        //将所有的域拉出来
        //        List<string> fields = new List<string>();


        //        //6、遍历文档中的变量，设置变量内容
        //        foreach (var var in acDoc.Variables)
        //        {
        //            if (var.Name.StartsWith(Dics.WORD_FIELD_TAG))
        //            {
        //                var fieldName = var.Name.Substring(Dics.WORD_FIELD_TAG.Length);
        //                if (pageDic.ContainsKey(fieldName))
        //                    var.Value = pageDic[fieldName].value;
        //            }
        //        }
        //        System.Windows.Forms.Application.DoEvents();
        //        //7、变量文中的图片。 来替换图片
        //        foreach (var shape in acDoc.InlineShapes)
        //        {
        //            if (shape.Title.StartsWith(Dics.WORD_FIELD_TAG))
        //            {
        //                if (!string.IsNullOrEmpty(shape.Title) && shape.Title.StartsWith(Dics.WORD_FIELD_TAG))
        //                {
        //                    var trueName = shape.Title.Substring(Dics.WORD_FIELD_TAG.Length);
        //                    var imageType = trueName.Substring(0, 11); //image_group and image_image all is 11
        //                    //if (imageType.Equals(Dics.word_file_image_image))
        //                    //{
        //                    trueName = trueName.Substring(11);
        //                    //}
        //                    //else
        //                    //{
        //                    //    trueName = imageType;
        //                    //}
        //                    var updateTimeLong = long.Parse(formDs.Tables[0].Rows[0][frm_update_time].ToString());
        //                    var id = formDs.Tables[0].Rows[0][frm_form_id].ToString();
        //                    var updateTime = Utility.TimeStampToDateTime(updateTimeLong);
        //                    var date = updateTime.ToString("yyyy-MM-dd");
        //                    if (imageType.Equals(Dics.word_file_image_image))
        //                    {

        //                        var b = ServerApi.DownLoadCustomFile(date, id, trueName + ".jpg", (int)(shape.Width / 0.75), (int)(shape.Height / 0.75), trueName + ".jpg");
        //                        System.Windows.Forms.Application.DoEvents();
        //                        FileInfo info = new FileInfo(trueName + ".jpg");
        //                        if (info.Exists && info.Length > 0)
        //                        {
        //                            var shape2 = acDoc.InlineShapes.AddPicture(System.IO.Path.GetFullPath(trueName + ".jpg"), Type.Missing, Type.Missing, shape.Range);
        //                            System.Windows.Forms.Application.DoEvents();
        //                            var title = shape.Title;
        //                            shape.Delete();
        //                            shape2.Title = title;
        //                        }
        //                        info.Delete();
        //                    }
        //                    else if (imageType.Equals(Dics.word_file_image_group))
        //                    {
        //                        var files = ServerApi.GetFiles(date, id);
        //                        System.Windows.Forms.Application.DoEvents();
        //                        var theFiles = files.Where(the => the.fileName.StartsWith(trueName + "_"));

        //                        foreach (var each in theFiles)
        //                        {
        //                            var b = ServerApi.DownLoadCustomFile(date, id, each.fileName, (int)(shape.Width / 0.75), (int)(shape.Height / 0.75), each.fileName);
        //                            System.Windows.Forms.Application.DoEvents();
        //                            FileInfo info = new FileInfo(each.fileName);
        //                            if (info.Exists && info.Length > 0)
        //                            {
        //                                var shape2 = acDoc.InlineShapes.AddPicture(System.IO.Path.GetFullPath(each.fileName), Type.Missing, Type.Missing, shape.Range);
        //                                System.Windows.Forms.Application.DoEvents();
        //                                var title = shape.Title;
        //                                shape2.Title = title;
        //                            }
        //                            info.Delete();
        //                        }
        //                        shape.Delete();
        //                    }

        //                }
        //            }
        //        }

        //        acDoc.Fields.Update();

        //        acDoc.Application.Visible = true;
        //        acDoc.Activate();
        //        acDoc.Application.Activate();

        //    }
        //    finally
        //    {
        //        loading.Close();
        //    }

        //    return null;
        //}


        ///// <summary>
        ///// 从服务器下载模版至本地
        ///// </summary>
        ///// <param name="fileId"></param>
        ///// <returns></returns>
        //private string DownLoadSiteModelFromServer(string fileId, string updateTimeStr, out string errorStr)
        //{
        //    var saveFileName = GetLocalPath() + fileId + "." + updateTimeStr + ".docx";
        //    var result = FileOperation.DownLoadFile(fileId, saveFileName, Dics.GetDbClient(), Dics.uploadPathForWord);
        //    if (result == null)
        //    {
        //        errorStr = null;
        //        return saveFileName;
        //    }
        //    else
        //    {
        //        errorStr = result;
        //        return null;
        //    }
        //}

        //private string GetLocalPath()
        //{
        //    if (basePath == null) basePath = CpdatCloudClient.Interop.CommonUitiliy.GetCodeBase(this.GetType());
        //    return basePath + "\\SiteTable\\";
        //}
    }
}
